classdef GlobalPacketDepositor < Singleton & ClockHandler
    %GLOBALPACKETDEPOSITOR Summary of this class goes here
    %   Detailed explanation goes here
    
    properties
        packets_per_node_arr = [];
    end
    
    methods(Static)
        function obj = instance(should_reinit)
         persistent unique_instance;
         should_reinit = (nargin>0);
         if isempty(unique_instance) || (should_reinit==true)
            unique_instance = GlobalPacketDepositor();
         end
         obj = unique_instance;
        end
   end
    
    methods
        function obj = GlobalPacketDepositor()
            %register on clock tick
            ck = ClockSingleton.instance();
            ck.register_for_clock_ticks(obj);
        end
        
        function set_nodes(obj, nodes)
            num_of_nodes = length(nodes);
            packets_per_node_vec(1,num_of_nodes) = PacketsPerNodeStruct();
            obj.packets_per_node_arr = packets_per_node_vec;
            for i=1:num_of_nodes
                obj.packets_per_node_arr(i).node = nodes(i);
            end
        end
        
        function deposit_packet_to_node(obj, node_id, multi_packet)
            curr_struct = obj.packets_per_node_arr(node_id);
            assert(curr_struct.num_of_packets < ParamsSingleton.instance().max_number_of_packets_per_node_allowed_per_tick);
            curr_index = curr_struct.num_of_packets + 1;
            curr_struct.multi_packets(curr_index) = multi_packet;
            curr_struct.num_of_packets = curr_struct.num_of_packets+1;
        end
        
        function clock_tick_handler(obj)
            %deposit all packets to their nodes
            for i=1:length(obj.packets_per_node_arr)
                curr_node = obj.packets_per_node_arr(i).node;
                num_of_packets = obj.packets_per_node_arr(i).num_of_packets;
                if num_of_packets>0
                    fprintf('GlobalDepositor: depositing %d packets to node %d\n', num_of_packets,curr_node.id);
                    multi_packets = obj.packets_per_node_arr(i).multi_packets;
                    curr_node.deposit_packets_for_this_tick(multi_packets(1:num_of_packets));
                    %should i regenrate the vector here?
                    obj.packets_per_node_arr(i).num_of_packets = 0;
                end
            end
        end
    end
    
end

